//
//  BLLoginController.m
//  Byelone
//
//  Created by 乔小乔 on 2021/1/12.
//

#import "BLLoginController.h"
#import "BLRegisterController.h"
#import "BLLogin_Model.h"
#import "BLInfoAvatarController.h"
#import "BLInfoInputController.h"
#import "BLForgetPsdVC.h"

@interface BLLoginController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIButton *btnLogin;
@property (weak, nonatomic) IBOutlet UIButton *btnService;
@property (weak, nonatomic) IBOutlet UIView *viewPhone;
@property (weak, nonatomic) IBOutlet UIView *viewPassWord;
@property (weak, nonatomic) IBOutlet UITextField *textFieldPhone;//手机号
@property (weak, nonatomic) IBOutlet UITextField *textFieldPassWord;//密码
@property (weak, nonatomic) IBOutlet UITextField *textFieldCode;//验证码
@property (weak, nonatomic) IBOutlet UITextField *textFieldCodePhone;//验证码手机号
@property (weak, nonatomic) IBOutlet UIButton *btnSendCode;
@property (weak, nonatomic) IBOutlet UIButton *btnPsd;
@property (weak, nonatomic) IBOutlet UIButton *btnSms;
@property (weak, nonatomic) IBOutlet UIButton *btnSelect;
@property (weak, nonatomic) IBOutlet UIView *viewSliderPsd;
@property (weak, nonatomic) IBOutlet UIView *viewSliderSms;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger totalTime;
@end

@implementation BLLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"密码登录";
    [self.textFieldCodePhone addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    [self createUI];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    [self.btnLogin setGradientBackgroundWithColors:@[[UIColor chColorWithHexString:@"#8881FD"],[UIColor chColorWithHexString:@"#6B71F5"]] locations:@[@(0.0f), @(1.0f)]  startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
}
- (void)leftAction{
    if (self.failBlock) {
        self.failBlock();
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)createUI{
    [self dispossUIData];
//    [self.btnService setAttributedTitle:[self getAttStrWith:@"《服务协议》"] forState:UIControlStateNormal];
}
//下划线按钮的设置
- (NSMutableAttributedString *)getAttStrWith:(NSString *)string{
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:string];
    [attr addAttributes:@{NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)} range:NSMakeRange(0, string.length)];
    [attr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"PingFangSC-Regular" size:11] range:NSMakeRange(0, string.length)];
    [attr addAttributes:@{NSForegroundColorAttributeName:[UIColor chColorWithHexString:@"#6D72F6"]} range:NSMakeRange(0, string.length)];
    [attr addAttributes:@{NSUnderlineColorAttributeName:[UIColor chColorWithHexString:@"#6D72F6"]} range:NSMakeRange(0, string.length)];
    return attr;
}
//根据状态切换页面
- (void)dispossUIData{
    self.viewPhone.hidden = (self.loginType==BLLoginTypePhone)?NO:YES;
    self.viewPassWord.hidden = (self.loginType==BLLoginTypePhone)?YES:NO;
    NSString *strLogin = (self.loginType==BLLoginTypePhone)?@"确认注册/登录":@"确认登录";
    [self.btnLogin setTitle:strLogin forState:UIControlStateNormal];
    self.navigationItem.title = (self.loginType==BLLoginTypePhone)?@"验证码登录":@"密码登录";
}
- (void)dealloc{
    if (self.timer!=nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (IBAction)clickChange:(UIButton *)sender {
    if (sender.selected) {
        return;
    }    
    sender.selected = YES;
    if (self.loginType==BLLoginTypePhone) {
        self.loginType=BLLoginTypePassWord;
        self.btnSms.selected = NO;
        self.viewSliderSms.hidden = YES;
        self.viewSliderPsd.hidden = NO;
        if (self.timer!=nil) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }else{
        self.loginType=BLLoginTypePhone;
        self.btnPsd.selected = NO;
        self.viewSliderPsd.hidden = YES;
        self.viewSliderSms.hidden = NO;
    }
    [self dispossUIData];
}

- (IBAction)clickSendCode:(UIButton *)sender {
    if (!sender.selected) {
        return;
    }
    NSDictionary *dict = @{@"phone":self.textFieldCodePhone.text?:@"",@"type":@"2"};
    [BLHttpTool postWithPath:BL_USER_SMSCODE params:dict successBlock:^(NSDictionary * _Nonnull obj) {
        if (obj&&[obj isKindOfClass:[NSDictionary class]]) {
            sender.selected = NO;
            if (self.timer!=nil) {
                [self.timer invalidate];
                self.timer = nil;
            }
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeHeadle) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
            self.totalTime = 60;
            sender.userInteractionEnabled = NO;
            [sender setTitle:@"60s" forState:UIControlStateNormal];
        }
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"%@",error);
        }
    }];
}
- (IBAction)clickLogin:(id)sender {
    NSString *strUrl =BL_USER_LOGIN;
    NSDictionary *dict = [[NSDictionary alloc]init];
    if (self.loginType == BLLoginTypePassWord) {
        if (self.textFieldPhone.text.length<11) {
            [HUD showtip:@"请输入正确手机号"];
            return;
        }
        if (self.textFieldPassWord.text.length<=0) {
            [HUD showtip:@"请输入密码"];
            return;
        }
        dict = @{@"account":self.textFieldPhone.text?:@"",@"password":self.textFieldPassWord.text?:@""};
    }else{
        if (self.textFieldCodePhone.text.length<11) {
            [HUD showtip:@"请输入正确手机号"];
            return;
        }
        if (self.textFieldCode.text.length<=0) {
            [HUD showtip:@"请输入验证码"];
            return;
        }
        strUrl = BL_USER_LOGINBYPHONE;
        dict = @{@"phone":self.textFieldCodePhone.text?:@"",@"smsCode":self.textFieldCode.text?:@""};
    }
    if (!self.btnSelect.selected) {
        [HUD showtip:@"请阅读并同意用户协议"];
        return;
    }
    
    [BLHttpTool postWithPath:strUrl params:dict successBlock:^(NSDictionary * _Nonnull obj) {
        if (obj&&[obj isKindOfClass:[NSDictionary class]]) {
            BLLogin_Model *model = [BLLogin_Model mj_objectWithKeyValues:obj[@"content"]];
//            存储用户token
            [BLUserManager shareUser].userPpu = model.ppu;
            [BLUserManager shareUser].registerStep = model.registerStep;
            [BLUserManager shareUser].phone = self.textFieldPhone.text;

            if ([model.registerStep isEqualToString:@"1"]) {
                [BLTool getCurrentNavigationController];
                BLInfoAvatarController *vc = [[BLInfoAvatarController alloc]init];
                vc.loginBlock = self.loginBlock;
                [[BLTool getCurrentNavigationController] pushViewController:vc animated:YES];
            }else if ([model.registerStep isEqualToString:@"2"]){
                BLInfoInputController *vc = [[BLInfoInputController alloc]init];
                vc.loginBlock = self.loginBlock;
                [[BLTool getCurrentNavigationController] pushViewController:vc animated:YES];
            }else{
                if (self.onlyBlock) {
                    self.onlyBlock();
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:Notification_login object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
    
}
- (IBAction)clickService:(UIButton *)sender {
    NSInteger index = sender.tag;
    if (index == 101) {//服务协议
        
    }else if (index == 102){//隐私政策
        
    }
}
- (IBAction)clickAgree:(UIButton *)sender {
    sender.selected = !sender.selected;
}
- (IBAction)clickScrect:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.textFieldPassWord.secureTextEntry = !sender.selected;
}
- (IBAction)clickOther:(UIButton *)sender {
    if (sender.tag == 1001) {
        BLRegisterController *vc = [[BLRegisterController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag == 1002){
        BLForgetPsdVC *vc = [[BLForgetPsdVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag == 1003){
        if (self.failBlock) {
            self.failBlock();
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)timeHeadle{
    self.totalTime --;
    if (self.totalTime<=0) {
        [self.btnSendCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.btnSendCode.userInteractionEnabled = YES;
        self.btnSendCode.selected = YES;
    }else{
        [self.btnSendCode setTitle:[NSString stringWithFormat:@"%lds",self.totalTime] forState:UIControlStateNormal];
    }
}
#pragma mark - delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == self.textFieldPhone||textField == self.textFieldCodePhone) {
        if (textField.text.length>=11&&string.length>0) {
            return NO;
        }
    }
    
    return YES;
}

- (void)textChange:(UITextField *)textField{
    if (textField == self.textFieldCodePhone) {//这个判断要加在别处
        if (textField.text.length==11) {
            self.btnSendCode.selected = YES;
        }else{
            self.btnSendCode.selected = NO;
        }
        
    }
}
@end
